package com.joint.web.action.com;


import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.bean.Result;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.service.*;
import com.joint.base.service.activiti.WorkflowService;
import com.joint.base.service.activiti.WorkflowTraceService;
import com.joint.base.util.DataUtil;
import com.joint.base.util.EntityConfig;
import com.joint.base.util.FileUtil;
import com.joint.base.util.WorkflowUtils;
import com.joint.core.entity.manage.Notice;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONObject;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.core.io.ResourceLoader;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.ZipInputStream;


@ParentPackage("com")
public class AjaxTaskrecordAction extends BaseAdminAction {

    @Resource
    private UsersService usersService;
    @Resource
    private TaskRecordService taskRecordService;
    @Resource
    private WorkflowService workflowService;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private HistoryService historyService;
    @Resource
    private TaskService taskService;
    @Resource
    private TaskFlowService taskFlowService;
    //add by zhucx
    @Resource
    private TaskEntityService taskEntityService;
    //add by zhucx
    private static final EntityConfig entityConfig  = new EntityConfig();

    protected Logger logger = LoggerFactory.getLogger(getClass());
    //已办的类型
    private String type;


    /**
     * 返回视图
     * @return
     */
    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }

        // Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("state",BaseEnum.StateEnum.Enable);
        params.put("users", user);
        params.put("type", StringUtils.isNotEmpty(type)?Integer.parseInt(type):null);
        pager= taskRecordService.findByPager(pager,  params);
        List<TaskRecord> taskRecordList = (List<TaskRecord>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(TaskRecord taskRecord: taskRecordList){
            rMap = new HashMap<String, Object>();
           // String bussinessKey = taskRecord.getBussinessKey();
            String bussinessId = taskRecord.getKeyId();
            String usernames = "";
            String pname = "";
            String url = "";
            String model = "";
            TaskEntity taskEntity = null;
            if(StringUtils.isNotEmpty(bussinessId)){
                taskEntity = taskEntityService.getInfoByKeyId(bussinessId);
                pname = entityConfig.getValues(taskEntity.getEntityName());
                if(StringUtils.isNotEmpty(taskEntity.getEntityName())){
                    entityName = taskEntity.getEntityName().substring(taskEntity.getEntityName().lastIndexOf(".")+1).toLowerCase();
                }
                if(StringUtils.equals(taskRecord.getModule(), "行政管理")){
                    model="manage";
                }else if(StringUtils.equals(taskRecord.getModule(), "党政管理")){
                    model="party";
                }else if(StringUtils.equals(taskRecord.getModule(), "财务管理")){
                    model="finance";
                }else{
                    model="com";
                }
                url =  "../" + model + "/ajax-" + entityName + "!read.action?keyId=" +bussinessId  ;
                if(StringUtils.equals(type, "1")){
                    url +="&record=1";
                }else if(StringUtils.equals(type,"2")){
                    url +="&record=2";
                }
            }
            rMap.put("creater", taskEntity!=null?taskEntity.getCreater().getName():"");
            rMap.put("pname",pname);
            if(taskEntity != null && taskEntity.getEditors() != null){
                for(Users users :taskEntity.getEditors()){
                    usernames += users.getName()+",";
                }
            }
            if(StringUtils.isNotEmpty(usernames)){
                usernames = usernames.substring(0, usernames.length()-1);
            }
            rMap.put("usernames", usernames);
            rMap.put("id", taskRecord.getId());
            rMap.put("module",taskRecord.getModule());
            rMap.put("createDate", DataUtil.DateToString(taskRecord.getCreateDate(), "yyyy-MM-dd"));
            rMap.put("url",url);
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);

        }


        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    /**
     * 返回视图
     * @return
     */
    public String list1(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }

       // Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("state",BaseEnum.StateEnum.Enable);
        params.put("users", user);
        params.put("type", StringUtils.isNotEmpty(type)?Integer.parseInt(type):null);
        pager= taskRecordService.findByPager(pager,  params);
        List<TaskRecord> taskRecordList = (List<TaskRecord>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(TaskRecord taskRecord: taskRecordList){
            rMap = new HashMap<String, Object>();
            String bussinessKey = taskRecord.getBussinessKey();
            String bussinessId = taskRecord.getKeyId();
            String usernames = "";
            String pname = "";
            String url = "";
            String model = "";
            if(StringUtils.isNotEmpty(bussinessKey)){
                String key =  bussinessKey.toLowerCase().substring(bussinessKey.lastIndexOf(".")+1);
                ProcessDefinition processDefinition = workflowService.getProDefinitionByKey(key);
                pname = StringUtils.isEmpty(processDefinition.getName())?repositoryService.createDeploymentQuery().deploymentId(processDefinition.getDeploymentId()).list().get(0).getName():processDefinition.getName();
                if(StringUtils.equals(taskRecord.getModule(),"行政管理")){
                    model="manage";
                }else if(StringUtils.equals(taskRecord.getModule(),"党政管理")){
                    model="party";
                }else if(StringUtils.equals(taskRecord.getModule(),"财务管理")){
                    model="finance";
                }else{
                    model="com";
                }
                url =  "../" + model + "/ajax-" + processDefinition.getKey() + "!read.action?keyId=" +bussinessId  ;
                if(StringUtils.equals(type,"1")){
                    url +="&record=1";
                }else if(StringUtils.equals(type,"2")){
                    url +="&record=2";
                }
            }
            if(StringUtils.isNotEmpty(bussinessId)){
                List<HistoricProcessInstance> hpiList = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(bussinessId).list();
                if(hpiList.size()>0){
                    String  proInstanceId = hpiList.get(0).getId();
                    List<Task> taskList = taskService.createTaskQuery().processInstanceId(proInstanceId).active().orderByTaskCreateTime().desc().list();
                    for(Task task:taskList){
                        //新建和退回状态从activity流程引擎选，其他从自定义任务流程数据中查
                        if (StringUtils.equals(task.getTaskDefinitionKey(),"usertask1") ){
                            if(StringUtils.isNotEmpty(task.getAssignee())){
                                Users users = usersService.get(task.getAssignee());
                                usernames += users.getName()+",";

                            }
                        }else{
                            List<Users> usersList = taskFlowService.findUsersByTaskFlow(task.getId());
                            for(Users users:usersList){
                                usernames += users.getName()+ ",";
                            }
                        }
                    }
                }
                if(StringUtils.isNotEmpty(usernames)){
                    usernames = usernames.substring(0, usernames.length()-1);
                }


            }
            rMap.put("pname",pname);
            rMap.put("usernames", usernames);
            rMap.put("id", taskRecord.getId());
            rMap.put("module",taskRecord.getModule());
            rMap.put("createDate", DataUtil.DateToString(taskRecord.getCreateDate(), "yyyy-MM-dd"));
            rMap.put("url",url);
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);

        }


        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }




    public Logger getLogger() {
        return logger;
    }

    public void setLogger(Logger logger) {
        this.logger = logger;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}
